#!/usr/bin/env python
#
# Stack machine model for the SLDT example
#
# Author:   Mike Murphy <mamurph@cs.clemson.edu>
# Revision: 7 January 2009
#
# Copyright 2008-2009 Clemson University
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# This material is based upon work supported under a National Science
# Foundation Graduate Research Fellowship. Any opinions, findings,
# conclusions or recommendations expressed in this publication are those of
# the author(s) and do not necessarily reflect the views of the National
# Science Foundation.


# HINT: If SLDT had floating-point support, it would be possible to model
# the floating-point stack with a second instance of StackModel, e.g.:
#
# floatstack = StackModel('float')

WATCH=False

def watch(stackname, msg):
   if WATCH:
      print '*STACK <%s>*:' % stackname, msg
#

class StackModel(object):
   def __init__(self, whichstack='int'):
      self.size = 0
      self.name = whichstack
      self.maxsize = 0
   def push(self, count = 1):
      self.size += count
      watch(self.name, 'added %d items, size now %d' % (count, self.size))
      if self.size > self.maxsize:
         self.maxsize = self.size
         watch(self.name, 'new maximum size observed: %d' % self.maxsize)
   def consume(self, num):
      success = True
      if num > self.size:
         watch(self.name, 'consumption failure: size %d, requested %d' % \
               (self.size, num))
         success = False
      else:
         self.size -= num
         watch(self.name, 'consumed %d items, size now %d' % (num, self.size))
      return success
   def isEmpty(self):
      return (self.size == 0)
   def getMaxSize(self):
      return self.maxsize
   def __repr__(self):
      return ('Stack <%s> size: %d' % (self.name, self.size))
#

if __name__ == '__main__':
   stack = StackModel()
   stack.push()
   stack.push()
   print stack
   stack.consume(1)
   print stack
   print stack.consume(3)
   print stack
#
